// packageA/pages/equipmentEnter/equipmentEnter.js
const app = getApp();
import CommonService from '../../../utils/service/commonService.js';
import Toast from '../../../miniprogram_npm/@vant/weapp/toast/toast';
import Base64 from '../../../utils/Base64.js';
const util = require('../../../utils/util');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    //传参
    paramObj:null,
    //传参来的id
    id:null,    
    //修改信息回显
    editInfo:{},
    //提交按钮禁用
    disabled:false,
    //避免表单重复提交
    code:null,
    //选择框
    showSelect:false,
    //选择数据
    selectList:[],
    //当前选择
    selectField:'',
    //选择框标题
    selectTitle:'',
    //显示选择搜索框
    showSelectSearch:false,
    //折叠面板
    activeNames: null,
    //物流折叠面板
    logisticsActive: null,
    //查看or入库
    mark:'',
    //物流列表
    logisticsList:[]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      code:Base64.encode(new Date() + app.globalData.userInfo.userName)
    })

    if(options.paramObj){
      let paramObj=JSON.parse(options.paramObj);
      console.log('设备入库传参');
      console.log(paramObj);

      this.setData({
        paramObj: paramObj,
        mark: paramObj.mark
      })

      if(paramObj.id){
        this.setData({
          id: paramObj.id
        })
        //获取修改的数据
        this.getInfo();
      }
    }
  },  

  //提交表单
  confirmForm(e){
    //避免表单重复提交-先禁用按钮
    this.setData({
      disabled:true
    })

    let obj=e.detail.value;
    let editInfo=this.data.editInfo;  

    let param={
      id: this.data.id,
      //记账人
      keepAccounts: editInfo.keepAccounts ? editInfo.keepAccounts : null,
      //验收人
      checking: editInfo.checking ? editInfo.checking : null,
      //备注
      remark:obj.remark.trim(),
      //状态
      state: 1,
      //入库时间
      createDate: util.timeFormat(editInfo.createDate),
      //小程序平台
      appId: [app.globalData.myAppId],
      //数据权限-当前登录用户权限
      dataAuthority:{
        depart: [app.globalData.userInfo.depart]
      },

      //入库单的信息
      orderNo: editInfo.orderNo,
      splitRecordData: editInfo.splitRecordData,      
      destination: editInfo.destination,      
      depot: editInfo.depot,
      inStorageType: editInfo.inStorageType,
      handler: editInfo.handler,
      service: editInfo.service,
      orderObj: editInfo.orderObj,
      returnOrderNo: editInfo.returnOrderNo,
      returnOrderType: editInfo.returnOrderType,
      relationOrderNo: editInfo.relationOrderNo,
      agreementNo: editInfo.agreementNo ? editInfo.agreementNo : ''
    }

    //避免表单重复提交
    Toast.loading({
      duration: 0,
      forbidClick: true,
      message: '数据提交中...'
    });

    console.log(param);

    CommonService.returnOrder(param).then(res=>{
      this.setData({
        disabled:false
      })
      if (res.statusCode == 200 && res.data.success == true){
        Toast.success('成功');
        setTimeout(() => {
          //返回列表页并刷新数据
          this.backAndRefresh();
        }, 1000);
      }else{
        Toast.fail('操作失败');
      }
    }).catch((error) => {
      Toast.fail('操作失败');
    })
  },

  //获取修改的数据
  getInfo(){
    let param = {
      isAuth: false,
      className: 'inStorageOrder',
      data: {
        id:this.data.id,
        selectFields: ["id","orderNo", "splitRecordData", 'type', 'createDate', 'state', 'operator','returnOrderNo', 'relationOrderNo', 'inStorageType', 'remark','destination','depot','service','handler','prepared','inputDateTime','keepAccounts','checking','orderObj','dataAuthority','returnOrderType','agreementNo']
      }
    }

    CommonService.goFindList(param).then(res => {
      if(res.data.data && res.data.data.result && res.data.data.result.length) {
        let result=res.data.data.result[0];        
        //入库时间
        if(result.inputDateTime){
          result.inputDateTime=util.timeFormat(result.inputDateTime);
        }

        if(result.splitRecordData && result.splitRecordData.length){
          let nos=[];
          result.splitRecordData.forEach(item => {
            if(item.equipmentNo){
              nos.push(item.equipmentNo);
            }
          });    

          //获取物流信息
          this.getLogistics(nos);
        }

        console.log('设备入库回显');
        console.log(result);
       
        this.setData({
          editInfo: result
        })
      }
    }).catch((error) => {
    })
  }, 

  //切换折叠面板
  onChange(event) {
    this.setData({
      activeNames: event.detail,
    })
  },

  //切换物流折叠面板
  onChangeLogistics(event) {
    this.setData({
      logisticsActive: event.detail,
    })
  },

  //返回列表页并刷新数据
  backAndRefresh(){
    let pages = getCurrentPages();
    let prevPage = pages[pages.length - 2];

    prevPage.refreshListAndPage();
    wx.navigateBack();
  },  

  //显示选择框
  onShowSelect(e){
    this.setData({
      selectList: []
    })

    let dataset=e.target.dataset;
    let field=dataset.field;

    this.setData({
      showSelect: true,
      selectField: field
    })

    //记账
    if(field=='accounts'){
      this.setData({
        selectTitle: '记账人员',
        showSelectSearch: true
      })
      this.getStaffList();
    }

    //验收
    if(field=='check'){
      this.setData({
        selectTitle: '验收人员',
        showSelectSearch: true
      })
      this.getStaffList();
    }
  },

  //隐藏选择框
  onCloseSelect(){
    this.setData({
      showSelect: false,
      valueSearch: '',
      disabled: false
    })
  },

  //确认选项
  onConfirmSelect(e){
    let selectField=this.data.selectField;
    let id=null,name=null,obj=null;

    //记账
    if(selectField=='accounts'){
      obj='editInfo.keepAccounts';
    }

    //验收
    if(selectField=='check'){
      obj='editInfo.checking';
    }

    if(id && name){
      this.setData({
        [id]:e.detail.value.id,
        [name]:e.detail.value.text
      })
    }

    if(obj){
      this.setData({
        [obj]:e.detail.value.obj
      })
    }

    this.onCloseSelect();
  },

  //清除选项
  onCancelSelect(){
    let selectField=this.data.selectField;
    let id=null,name=null,obj=null;

    //记账
    if(selectField=='accounts'){
      obj='editInfo.keepAccounts';
    }

    //验收
    if(selectField=='check'){
      obj='editInfo.checking';
    }

    if(id && name){
      this.setData({
        [id]:null,
        [name]:''
      })
    }

    if(obj){
      this.setData({
        [obj]:null
      })
    }

    this.onCloseSelect();
  },

  //选择框搜索
  onChangeSelectVal(e){
    let selectField=this.data.selectField;

    this.setData({
      valueSearch: e.detail
    })

    //记账，验收
    if(selectField=='accounts' || selectField=='check'){
      this.getStaffList();
    }
  },

  //查询人员
  getStaffList(){
    let param = {
      isAuth: true,
      className: 'user',
      data: {
        depart: 1,
        searchAll: true,
        selectFields: ['id','userName']
      }
    }

    if(this.data.valueSearch){
      param.data.userName='%' + this.data.valueSearch + '%';
    }

    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result;
        let arr=[];
        result.forEach(item => {
          arr.push({
            text:item.userName,
            id:item.id,
            obj:{
              id:item.id,
              name:item.userName
            }
          });
        });

        this.setData({
          selectList: arr
        })
      }
    }).catch((error) => {
    })
  },

  //预览图片
  onPreviewImage(e) {
    let detail = e.target.dataset.detail;
    let src = e.target.dataset.src;

    let newArr=[];
    for(let i=0;i<detail.length;i++){
      newArr.push(detail[i].url);
    }

    wx.previewImage({
      current: src,
      urls: newArr
    })
  },

  //获取物流信息
  getLogistics(arr){
    let param = {
      isAuth: true,
      className: 'returnLogistics',
      data: {
        equipment: arr,
        searchAll: true,
        sort: {"createDate":-1},
        selectFields: ["id","returnOrderNo","equipment","logisticsName","logisticsNo","logisticsTime","remark","equipmentOption","phone"]
      }
    }


    CommonService.goFindList(param).then(res => {
      if(res.data.data && res.data.data.result && res.data.data.result.length) {
        let result=res.data.data.result;

        console.log('物流信息');
        console.log(result);

        //只有一条就展开物流信息
        if(result.length==1){
          this.setData({
            logisticsActive: 0
          })
        }

        this.setData({
          logisticsList: result
        })  
      }
    }).catch((error) => {
    }) 
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  }
})